package com.boot.stu.config.security;

import com.boot.stu.util.Oauth2Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import java.util.concurrent.TimeUnit;

/**
 * @author cwt
 * @description 认证授权服务器
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {


    private AuthenticationManager authenticationManager;
    public  AuthenticationManager setAuthenticationManager(AuthenticationManager authenticationManager){
        return  authenticationManager=authenticationManager;
    };
    @Autowired
    private RedisConnectionFactory connectionFactory;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        String finalSecret = "{bcrypt}" + new BCryptPasswordEncoder().encode(Oauth2Util.CLIENT_SECRET);
        //配置客户端，使用密码模式验证鉴权
        clients.inMemory()
                .withClient(Oauth2Util.CLIENT_ID)
                //密码模式及refresh_token模式
                .authorizedGrantTypes(Oauth2Util.GRANT_TYPE[0], Oauth2Util.GRANT_TYPE[1])
                .scopes("all")
                .secret(finalSecret);
    }

    @Bean
    public RedisTokenStore redisTokenStore() {
        return new RedisTokenStore(connectionFactory);
    }

    /**
     * @description token及用户信息存储到redis，当然你也可以存储在当前的服务内存，不推荐
     * @param endpoints
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        //token信息存到服务内存
            /*endpoints.tokenStore(new InMemoryTokenStore())
                    .authenticationManager(authenticationManager);*/

        //token信息存到redis
        endpoints.tokenStore(redisTokenStore()).authenticationManager(authenticationManager);
        //配置TokenService参数
        DefaultTokenServices tokenService = new DefaultTokenServices();
        tokenService.setTokenStore(endpoints.getTokenStore());
        tokenService.setSupportRefreshToken(true);
        tokenService.setClientDetailsService(endpoints.getClientDetailsService());
        tokenService.setTokenEnhancer(endpoints.getTokenEnhancer());
        //1小时
        tokenService.setAccessTokenValiditySeconds((int) TimeUnit.HOURS.toSeconds(1));
        //1小时
        tokenService.setRefreshTokenValiditySeconds((int) TimeUnit.HOURS.toSeconds(1));
        tokenService.setReuseRefreshToken(false);
        endpoints.tokenServices(tokenService);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        //允许表单认证
        oauthServer.allowFormAuthenticationForClients().tokenKeyAccess("isAuthenticated()")
                .checkTokenAccess("permitAll()");
    }
}
